// tableModelsCloud.js
// 定义系统支持的模型表
// 暂时通过nodejs实现，后面需要考虑迁移到独立的云端项目中
const path = require('path');
class ModelsCloudTable {
    constructor(app, db) {
        this.app = app;
        this.db = db;
    }

    // 每一个预定义模型打包后包含如下脚本
    async init() {
        // 创建models_cloud表格
        const sqlModelsTable = `
        CREATE TABLE IF NOT EXISTS models_cloud (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            eng_name TEXT NOT NULL,
            type TEXT NOT NULL,
            subtype TEXT NOT NULL,
            framework TEXT NOT NULL,
            version TEXT NOT NULL,
            desc TEXT NOT NULL,
            params_path TEXT DEFAULT '',
            params_size INTEGER DEFAULT 0,
            def_path TEXT DEFAULT '',
            conf_path TEXT DEFAULT '',
            script_jsproxy TEXT DEFAULT '',
            script_infer TEXT DEFAULT '',
            script_train TEXT DEFAULT '',
            script_eval TEXT DEFAULT '',
            script_env TEXT DEFAULT '',
            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );`;
        return new Promise((resolve, reject) => {
            this.db.run(sqlModelsTable, (err) => {
                if (err) {
                    console.error('Create "models_cloud" Table Failed, Error: ', err);
                    reject(err);
                } else {
                    resolve(this.lastID);
                }
            });
        });
    }

    // 插入models_cloud记录（暂时通过脚本调用，后续放到云端）
    // 参数定义modelInfos，具体名字是上述数据库的字段名，即：
    // name: 模型名称
    // eng_name: 模型英文名称
    // ...
    async insert(modelInfos) {
        // console.log('modelInfos = ', modelInfos);
        return new Promise((resolve, reject) => {
            const {
                id,
                name,
                eng_name,
                type,
                subtype,
                framework,
                version,
                desc,
                params_path,
                params_size,
                def_path,
                conf_path,
                script_jsproxy,
                script_infer,
                script_train,
                script_eval,
                script_env
            } = modelInfos;
            const sqlInsert = `
                INSERT INTO models_cloud (id, name, eng_name, type, subtype, framework, version, desc, params_path, params_size, def_path, conf_path, script_jsproxy, script_infer, script_train, script_eval, script_env, create_time, update_time )
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,  datetime(CURRENT_TIMESTAMP, '+8 hour') , datetime(CURRENT_TIMESTAMP, '+8 hour'));`;
            this.db.run(
                sqlInsert,
                [
                    id,
                    name,
                    eng_name,
                    type,
                    subtype,
                    framework,
                    version,
                    desc,
                    params_path,
                    params_size,
                    def_path,
                    conf_path,
                    script_jsproxy,
                    script_infer,
                    script_train,
                    script_eval,
                    script_env
                ],
                function (err) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(this.lastID);
                    }
                }
            );
        });
    }

    // 返回models_cloud列表
    async GetCloudModels(model_id) {
        let userDataPath = this.app.userDataPath;
        return new Promise((resolve, reject) => {
            const sqlQuery = `SELECT * FROM models_cloud${model_id ? ' WHERE id = ?' : ''};`;
            const params = model_id ? [model_id] : [];

            this.db.all(sqlQuery, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    const updatedRows = rows.map(row => {
                        return {
                            ...row,
                            def_path: path.join(userDataPath, row.def_path),
                            conf_path: path.join(userDataPath, row.conf_path),
                            script_jsproxy: path.join(userDataPath, row.script_jsproxy),
                            script_infer: path.join(userDataPath, row.script_infer),
                            script_train: path.join(userDataPath, row.script_train),
                            script_eval: path.join(userDataPath, row.script_eval),
                            script_env: path.join(userDataPath, row.script_env)
                        };
                    });
                    resolve(updatedRows);
                }
            });
        });
    }

    // 清空models_cloud列表（目的是为了更新数据）
    async clearModelsCloud() {
        return new Promise((resolve, reject) => {
            const sqlDelete = `DELETE FROM models_cloud;`;
            this.db.run(sqlDelete, [], function (err) {
                if (err) {
                    reject({ code: -1, msg: err.message });
                } else {
                    resolve({
                        code: 0,
                        msg: `Clear Models Cloud OK`
                    });
                }
            });
        });
    }
}

module.exports = { ModelsCloudTable };
